<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\service\business\controllers\Config\ConfigService;
use app\admin\validate\Config;
use think\facade\View;
use think\Request;

class ConfigController extends BaseController
{
    /** @var ConfigService */
    protected $server;

    protected function initialize()
    {
        $this -> server = ConfigService::getInstance();
    }

    /**
     * 获取规则
     *
     * @return string
     */
    private function getRule():string{
        return $this -> request -> rule() -> getRule();
    }

    /**
     * 显示资源列表
     *
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        $configType = $this -> getRule();

        if($this -> request -> isAjax()){
            // 请求参数
            $params = $this -> request -> get(['key']);

            // 配置类型
            $params['key']['type'] = $this -> server -> configType[$configType];

            return $this -> returnData(200, '请求成功', [
                'list' => $this -> server -> resList($params, $this -> request -> get('limit', 10, 'intval'))
            ]);
        }

        //
        return View::fetch('', [
            'configType' => $configType
        ]);
    }

    /**
     * 显示编辑资源表单页
     *
     * @param int $id
     * @return string
     * @throws \Exception
     */
    public function edit(int $id)
    {
        $result = $this -> server -> resFind($id);

        return View::fetch('form', [
            'data' => $result,
            'configType' => $this -> getRule()
        ]);
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param int $id
     * @return object
     */
    public function update(Request $request, int $id)
    {
        $params = $request -> param(['value', 'description', 'value_type']);

        $this -> validate($params, Config::class);

        $result = $this -> server -> operating($params, $id);

        return $this -> returnData($result['code'], $result['msg'], $result['data']);
    }
}
